<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="患者姓名" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入患者姓名"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="性别" prop="sex">
        <el-select style="width: 100px;" v-model="queryParams.sex" placeholder="请选择性别" clearable>
          <el-option
            v-for="dict in sys_user_sex"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="手机号码" prop="phone">
        <el-input
          v-model="queryParams.phone"
          placeholder="请输入手机号码"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['chy:patient:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['chy:patient:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['chy:patient:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['chy:patient:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="patientList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="患者卡号" align="center" prop="id" />
      <el-table-column label="患者姓名" align="center" prop="name" />
      <el-table-column label="性别" align="center" prop="sex">
        <template #default="scope">
          <dict-tag :options="sys_user_sex" :value="scope.row.sex"/>
        </template>
      </el-table-column>
      <el-table-column label="年龄" align="center" prop="age" />
      <el-table-column label="出生日期" align="center" prop="birthday" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.birthday, '{y}-{m}-{d} ') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="手机号码" align="center" prop="phone" />
      <!-- <el-table-column label="身份证号" align="center" prop="idNumber" /> -->
      <el-table-column label="患者来源" align="center" prop="department">
        <template #default="scope">
          <dict-tag :options="doctor_department" :value="scope.row.department"/>
        </template>
      </el-table-column>
      <el-table-column label="会员类型" align="center" prop="vipType">
        <template #default="scope">
          <dict-tag :options="doctor_vip" :value="scope.row.vipType"/>
        </template>
      </el-table-column>
      <el-table-column label="民族" align="center" prop="nation" />
      <el-table-column label="婚姻状况" align="center" prop="marriagestatus">
        <template #default="scope">
          <dict-tag :options="doctor_marriage" :value="scope.row.marriagestatus"/>
        </template>
      </el-table-column>
      <el-table-column label="详细地址" align="center" prop="address" />
      <el-table-column label="学历" align="center" prop="education">
        <template #default="scope">
          <dict-tag :options="doctor_education" :value="scope.row.education"/>
        </template>
      </el-table-column>
      <el-table-column label="职业" align="center" prop="career">
        <template #default="scope">
          <dict-tag :options="doctor_career" :value="scope.row.career"/>
        </template>
      </el-table-column>
      <el-table-column label="工作单位" align="center" prop="workUnit" />
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleaddFamily(scope.row)" v-hasPermi="['chy:patient:edit']">添加患者家庭关系</el-button>
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['chy:patient:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['chy:patient:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改患者信息对话框 -->
    <el-dialog :title="title" v-model="open" width="1000px" append-to-body>
      <el-form ref="patientRef" :model="form" :rules="rules" label-width="80px">
      <div class="add_first">
        <el-form-item label="患者姓名" prop="name">
          <el-input v-model="form.name" placeholder="请输入患者姓名" style="width: 200px;" />
        </el-form-item>
        <el-form-item label="性别" prop="sex" >
          <el-select v-model="form.sex" placeholder="请选择性别" style="width: 200px;">
            <el-option
              v-for="dict in sys_user_sex"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="年龄" prop="age" >
          <el-input v-model="form.age" placeholder="请输入年龄" style="width: 200px;" />
        </el-form-item>
      </div>
      <div class="add_two">
        <el-form-item label="出生日期" prop="birthday" >
          <el-date-picker clearable
            v-model="form.birthday"
            type="date"
            value-format="YYYY-MM-DD  HH:mm:ss"
            placeholder="请选择出生日期" style="width: 200px;">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="手机号码" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入手机号码"  style="width: 200px;"/>
        </el-form-item>
        <el-form-item label="身份证号" prop="idNumber">
          <el-input v-model="form.idNumber" placeholder="请输入身份证号" style="width: 200px;" />
        </el-form-item>
      </div>
      <div class="add_first">
        <el-form-item label="患者来源" prop="department">
          <el-select v-model="form.department" placeholder="请选择患者来源" style="width: 200px;">
            <el-option
              v-for="dict in doctor_department"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="会员类型" prop="vipType">
          <el-select v-model="form.vipType" placeholder="请选择会员类型" style="width: 200px;">
            <el-option
              v-for="dict in doctor_vip"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="民族" prop="nation">
          <el-input v-model="form.nation" placeholder="请输入民族" style="width: 200px;" />
        </el-form-item>
      </div>
      <div class="add_first">
        <el-form-item label="婚姻状况" prop="marriagestatus">
          <el-select v-model="form.marriagestatus" placeholder="请选择婚姻状况" style="width: 200px;">
            <el-option
              v-for="dict in doctor_marriage"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="学历" prop="education">
          <el-select v-model="form.education" placeholder="请选择学历" style="width: 200px;">
            <el-option
              v-for="dict in doctor_education"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="职业" prop="career">
          <el-select v-model="form.career" placeholder="请选择职业" style="width: 200px;">
            <el-option
              v-for="dict in doctor_career"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
      </div>
        <el-form-item label="详细地址" prop="address">
          <el-input v-model="form.address" placeholder="请输入详细地址" style="width: 500px;" />
        </el-form-item>
        <el-form-item label="工作单位" prop="workUnit">
          <el-input v-model="form.workUnit" placeholder="请输入工作单位" style="width: 500px;" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" style="width: 500px;" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 添加或修改患者家庭关系对话框 -->
    <el-dialog :title="title" v-model="open_family" width="700px" append-to-body>
      <el-form ref="familyRef" :model="form_family" :rules="rules_family" label-width="100px">
        <el-form-item label="家庭成员姓名" prop="name">
          <el-input v-model="form_family.name" placeholder="请输入家庭成员姓名" />
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-input v-model="form_family.age" placeholder="请输入年龄" />
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-select v-model="form_family.sex" placeholder="请选择性别">
            <el-option
              v-for="dict in sys_user_sex"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="家庭成员电话" prop="phone">
          <el-input v-model="form_family.phone" placeholder="请输入家庭成员电话" />
        </el-form-item>
        <el-form-item label="家庭成员关系" prop="relation">
          <!-- <el-input v-model="form.relation" placeholder="请输入家庭成员关系" /> -->
          <el-select v-model="form_family.relation" placeholder="请选择性别">
            <el-option
              v-for="dict in doctor_family"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="患者id" prop="pId">
          <el-input v-model="form_family.pId" placeholder="请输入患者id" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm_family">确 定</el-button>
          <el-button @click="cancel_family">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Patient">
import { listPatient, getPatient, delPatient, addPatient, updatePatient } from "@/api/chy/patient";
import { addFamily, updateFamily } from "@/api/chy/family";
const { proxy } = getCurrentInstance();
const { doctor_education, doctor_vip, doctor_career, sys_user_sex, doctor_department, doctor_marriage } = proxy.useDict('doctor_education', 'doctor_vip', 'doctor_career', 'sys_user_sex', 'doctor_department', 'doctor_marriage');
const { doctor_family } = proxy.useDict('doctor_family');
const patientList = ref([]);
const open = ref(false);
const open_family = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: null,
    sex: null,
    phone: null,
  },
  form_family: {},
  queryParams_family: {
    pageNum: 1,
    pageSize: 10,
    name: null,
    sex: null,
    phone: null,
  },
  rules: {
  },  
  rules_family: { 
  }
},
);

const { queryParams, form, rules,form_family,rules_family } = toRefs(data);

/** 查询患者信息列表 */
function getList() {
  loading.value = true;
  listPatient(queryParams.value).then(response => {
    patientList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}
// 取消按钮
function cancel_family() {
  open_family.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    name: null,
    password: null,
    sex: null,
    age: null,
    birthday: null,
    phone: null,
    idNumber: null,
    department: null,
    vipType: null,
    daedLine: null,
    nation: null,
    marriagestatus: null,
    address: null,
    education: null,
    career: null,
    workUnit: null,
    remark: null,
    del: null
  };
  form_family.value = {
    id: null,
    name: null,
    age: null,
    sex: null,
    phone: null,
    relation: null,
    del: null,
    pId: null
  };
  proxy.resetForm("familyRef");
  proxy.resetForm("patientRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

function handleaddFamily(row) {
  reset();
  form_family.value.pId = row.id; // 设置患者ID
  open_family.value = true;
  title.value = "添加患者家庭关系";
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加患者信息";
}


/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getPatient(_id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改患者信息";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["patientRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updatePatient(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addPatient(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}
// 提交家庭成员按钮
function submitForm_family(row) {
  form_family.pId = row.id;
  proxy.$refs["familyRef"].validate(valid => {
    if (valid) {
      if (form_family.value.id != null) {  // 注意这里改为 form_family
        updateFamily(form_family.value).then(response => {  // 注意这里改为 form_family
          proxy.$modal.msgSuccess("修改成功");
          open_family.value = false;  // 关闭家庭关系对话框
          // getList();  // 如果需要刷新列表可以取消注释
        });
      } else {
        addFamily(form_family.value).then(response => {  // 注意这里改为 form_family
          proxy.$modal.msgSuccess("新增成功");
          open_family.value = false;  // 关闭家庭关系对话框
          // getList();  // 如果需要刷新列表可以取消注释
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除患者信息编号为"' + _ids + '"的数据项？').then(function() {
    return delPatient(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('chy/patient/export', {
    ...queryParams.value
  }, `patient_${new Date().getTime()}.xlsx`)
}

getList();
</script>
<style>
.add_first{
  display: flex;
  justify-content: space-between;
}
.add_two{
  display: flex;
  justify-content: space-between;
  margin-top: 10px; 
}
</style>